package com.ayuku.commons;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.MathContext;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.eclipse.nebula.widgets.tablecombo.TableCombo;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.DateTime;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Monitor;
import org.eclipse.swt.widgets.Shell;

public class Util {

	public static String PERIODE_ID;

	public static MathContext ROUND_1 = new MathContext(1);
	public static MathContext ROUND_2 = new MathContext(2);
	public static int OPERATION_CODE = 0;

	public static void showMsgBox(final String msg, final int jns,
			final Shell dialogShell) {
		MessageBox message = new MessageBox(dialogShell, SWT.OK
				| SWT.ICON_INFORMATION);
		if (jns == 1) {
			message = new MessageBox(dialogShell, SWT.OK | SWT.ICON_WARNING);
		} else if (jns == 2) {
			message = new MessageBox(dialogShell, SWT.OK | SWT.ICON_ERROR);
		}
		message.setText(AYConst.APP_TITLE);
		message.setMessage(msg);
		message.open();
	}

	public static String cleanStr(String str) {
		if (str != null) {
			str.replace("'", "");
		}
		return str.trim();
	}
	public static String trimString(String ori, int length) {
		ori = Util.nullToString(ori);
		if (ori.length() > length) {
			ori = new String(ori.substring(0, length));
		}
		return new String(ori);
	}
	
	public static String nullToString(String str) {
		return (str == null) ? "" : str.trim();
	}

	public static String nullToString(Object obj) {
		return (obj == null) ? "" : String.valueOf(obj).trim();
	}

	public static Object nullToNumber(final Object obj) {
		return (obj == null) ? "0.00" : obj;
	}

	public static BigDecimal nullToBigDecimal(final Object obj) {
		return (obj == null) ? new BigDecimal(0.00) : (BigDecimal) obj;
	}

	public static Double nullToDouble(final Object obj) {
		return (obj == null) ? new Double(0.00) : (Double) obj;
	}

	public static Integer nullToInteger(final Object obj) {
		return (obj == null) ? new Integer("0") : Integer.valueOf(obj
				.toString());
	}

	public static Date nullToDate(final Date obj) {
		Date d = null;
		if (obj == null) {
			try {
				d = AYConst.TIMESTAMP_FORMAT.parse("1900-01-01 00:00:00");
				return d;
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		return obj;
	}

	public static Date getDefaultDate() {
		Date d = null;

		try {
			d = AYConst.TIMESTAMP_FORMAT.parse("1900-01-01 00:00:00");
			return d;
		} catch (Exception e) {
			e.printStackTrace();
		}

		return d;
	}

	public static boolean isEmpty(final String str) {
		boolean rtrn = false;

		if ((str == null) || str.trim().equals("")) {
			rtrn = true;
		}

		return rtrn;
	}

	public static void doGarbage() {
		final Runtime runti = Runtime.getRuntime();
		runti.gc();
	}

	public static String dateToString(Date arg) {

		if (arg == null) {
			return "";
		}

		Calendar cal = new GregorianCalendar();
		cal.setTime(arg);
		cal.set(Calendar.YEAR, 1900);
		cal.set(Calendar.DATE, 1);
		cal.set(Calendar.MONTH, 0);

		try {
			if (arg.equals(cal.getTime())) {
				return "";
			} else {
				return AYConst.DATE_FORMAT_FORM.format(arg);
			}
		} catch (Exception e) {
			return "";
		}
	}

	public static Calendar getCalendarFromDateTime(DateTime dt) {
		Calendar cal = Calendar.getInstance();
		cal.set(Calendar.DAY_OF_MONTH, dt.getDay());
		cal.set(Calendar.MONTH, dt.getMonth());
		cal.set(Calendar.YEAR, dt.getYear());
		cal.set(Calendar.HOUR_OF_DAY, dt.getHours());
		cal.set(Calendar.MINUTE, dt.getMinutes());
		cal.set(Calendar.SECOND, dt.getSeconds());

		return cal;
	}

	public static Calendar getCalendarFromSetting(DateTime dt) {
		Calendar cal = Calendar.getInstance();
		cal.set(Calendar.DAY_OF_MONTH, dt.getDay());
		cal.set(Calendar.MONTH, dt.getMonth());
		cal.set(Calendar.YEAR, dt.getYear());
		cal.set(Calendar.HOUR_OF_DAY, dt.getHours());
		cal.set(Calendar.MINUTE, dt.getMinutes());
		cal.set(Calendar.SECOND, dt.getSeconds());
		return cal;
	}

	public static void setDateTimeWithCalendar(Calendar cal, DateTime dt) {

		dt.setHours(cal.get(Calendar.HOUR));
		dt.setMinutes(cal.get(Calendar.MINUTE));
		dt.setSeconds(cal.get(Calendar.SECOND));
		dt.setYear(cal.get(Calendar.YEAR));
		dt.setMonth(cal.get(Calendar.MONTH));
		dt.setDay(cal.get(Calendar.DATE));

	}

	public static void setDateTimeWithDate(Date date, DateTime dt) {
		if (date == null) {
			return;
		}

		Calendar cal = Calendar.getInstance();
		cal.setTime(date);

		dt.setDay(cal.get(Calendar.DAY_OF_MONTH));
		dt.setMonth(cal.get(Calendar.MONTH));
		dt.setYear(cal.get(Calendar.YEAR));

		dt.setHours(cal.get(Calendar.HOUR_OF_DAY));
		dt.setMinutes(cal.get(Calendar.MINUTE));
		dt.setSeconds(cal.get(Calendar.SECOND));

	}

	public static long getDaysBtwTwoDate(Calendar start, Calendar end) {
		// Calculate difference in milliseconds
		long diff = end.getTimeInMillis() - start.getTimeInMillis();

		// Calculate difference in seconds
		// long diffSeconds = diff / 1000;

		// Calculate difference in minutes
		// long diffMinutes = diff / (60 * 1000);

		// Calculate difference in hours
		// long diffHours = diff / (60 * 60 * 1000);

		// Calculate difference in days
		// long diffDays = diff / (24 * 60 * 60 * 1000);

		return diff / (24 * 60 * 60 * 1000);
	}

	public static String dateTimeToString(DateTime dt) {
		return dt.getYear() + "-" + dt.getMonth() + "-" + dt.getDay();
	}

	public static String getShortDateTime(DateTime dt) {
		String strHour = dt.getHours() + "";
		String strMinute = dt.getMinutes() + "";

		if (strHour.length() < 2) {
			strHour = "0" + strHour;
		}
		if (strMinute.length() < 2) {
			strMinute = "0" + strMinute;
		}

		return strHour + ":" + strMinute;
	}

	public static String getAutoNoBukti() {
		Calendar cal = Calendar.getInstance();
		String tgl = cal.get(Calendar.YEAR) + cal.get(Calendar.MONTH)
				+ cal.get(Calendar.DATE) + cal.get(Calendar.HOUR)
				+ cal.get(Calendar.MINUTE) + cal.get(Calendar.SECOND) + "";
		return tgl;
	}

	public static Integer strToInt(String arg) {
		if (arg == null || "".equals(arg.trim())) {
			return null;
		}
		int in = 0;
		try {
			in = Integer.parseInt(arg.trim());
		} catch (Exception e) {

		}
		return Integer.valueOf(in);
	}

	public static BigDecimal strToBigDecimal(String arg) {
		if (arg == null || "".equals(arg.trim())) {
			return null;
		} else {
			Pattern p = Pattern.compile("([0-9]*)\\.([0-9]*)");
			Matcher m = p.matcher(arg.trim());
			if (m.matches()) {
				return new BigDecimal(arg.trim());
			} else {
				return null;
			}
		}
	}

	public static Double strToDouble(String arg) {
		if (arg == null || "".equals(arg.trim())) {
			return null;
		} else {
			return Double.valueOf(arg.trim());
		}
	}

	public static void setCenter(Shell shell) {
		Monitor primary = shell.getDisplay().getPrimaryMonitor();
		Rectangle bounds = primary.getBounds();
		Rectangle rect = shell.getBounds();
		int x = bounds.x + (bounds.width - rect.width) / 2;
		int y = bounds.y + (bounds.height - rect.height) / 2;
		shell.setLocation(x, y);
	}

	public static void setSize(Shell shell, int x, int y) {
		shell.setSize(x, y);
	}

	public static void setFull(Shell shell) {
		Monitor primary = shell.getDisplay().getPrimaryMonitor();
		Rectangle bounds = primary.getBounds();
		shell.setLocation(0, 0);
		shell.setSize(bounds.width, bounds.height - 30);
	}

	// get id from combo
	public static String getIdFromCmb(String strGrp) {
		String strId = null;
		if (strGrp != null) {
			int idx = strGrp.trim().indexOf("(");
			System.out.println("Index Of (: " + idx);
			if (!(idx < 0)) {
				strId = strGrp.substring((idx + 1),
						(strGrp.trim().length() - 1));
			}
			System.out.println("Grp: " + strId);
		}
		return strId;
	}

	// set combo selected
	public static void setCmbSelected(Combo cmb, String comp) {
		for (int i = 0; i < cmb.getItemCount(); i++) {
			System.out.println("item " + i + " " + cmb.getItem(i));
			String item = cmb.getItem(i);

			int idx = item.trim().indexOf("(");
			System.out.println("Index Of (: " + idx);
			String group = item
					.substring((idx + 1), (item.trim().length() - 1));
			System.out.println("Grp: " + group);
			if (group.equals(comp.toString())) {
			}

		}
	}

	public static BigDecimal getDecFromString(String strDec) {

		BigDecimal dc = new BigDecimal(0);
		try {
			dc = new BigDecimal(strDec);
		} catch (Exception e) {
			dc = new BigDecimal(0);
		}
		return dc;
	}

	public static Integer getIntFromString(String strDec) {
		Integer n = 0;
		try {
			n = new Integer(strDec);
		} catch (Exception e) {
			n = 0;
		}
		return n;
	}

	public static Date getDateFromStr(String strTgllahir) {
		Date birthDate = null;
		try {
			birthDate = AYConst.DATE_FORMAT_EXCEL.parse(strTgllahir);
		} catch (ParseException e) {
		}
		return birthDate;
	}

	public static String formatToNumber(BigDecimal dec) {
		if (dec == null) {
			return "0";
		}
		NumberFormat formatter = new DecimalFormat(
				"###,###,###,###.##;(###,###,###,###.##)");
		return formatter.format(dec);

	}

	public static String formatToNumber(Object value) {
		if (value == null) {
			return "0";
		}

		BigDecimal ret = null;
		if (value != null) {
			if (value instanceof BigDecimal) {
				ret = (BigDecimal) value;
			} else if (value instanceof String) {
				ret = new BigDecimal((String) value);
			} else if (value instanceof BigInteger) {
				ret = new BigDecimal((BigInteger) value);
			} else if (value instanceof Number) {
				ret = new BigDecimal(((Number) value).doubleValue());
			} else {
				throw new ClassCastException("Not possible to coerce [" + value
						+ "] from class " + value.getClass()
						+ " into a BigDecimal.");
			}
		}

		NumberFormat formatter = new DecimalFormat(
				"###,###,###,###.##;(###,###,###,###.##)");
		return formatter.format(ret);

	}

	public static String formatToNumber(Double dec) {
		if (dec == null) {
			return "0";
		}
		NumberFormat formatter = new DecimalFormat(
				"###,###,###,###.##;(###,###,###,###.##)");
		return formatter.format(dec);

	}

	public static String getIPAddress() {
		String ipAddress = null;
		try {
			java.net.InetAddress inet = java.net.InetAddress.getLocalHost();
			ipAddress = inet.getHostAddress() + "";
		} catch (Exception e) {

		}
		return ipAddress;
	}

	public static Date getCurrentDate() {
		Calendar cal = Calendar.getInstance();
		return cal.getTime();
	}

	public static String getSerialNumber(String drive) {
		String result = "";
		try {
			File file = File.createTempFile("realhowto", ".vbs");
			file.deleteOnExit();
			FileWriter fw = new java.io.FileWriter(file);

			String vbs = "Set objFSO = CreateObject(\"Scripting.FileSystemObject\")\n"
					+ "Set colDrives = objFSO.Drives\n"
					+ "Set objDrive = colDrives.item(\""
					+ drive
					+ "\")\n"
					+ "Wscript.Echo objDrive.SerialNumber"; // see note
			fw.write(vbs);
			fw.close();
			Process p = Runtime.getRuntime().exec(
					"cscript //NoLogo " + file.getPath());
			BufferedReader input = new BufferedReader(new InputStreamReader(
					p.getInputStream()));
			String line;
			while ((line = input.readLine()) != null) {
				result += line;
			}
			input.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result.trim();
	}

	public static String getMotherboardSN() {
		String result = "";
		try {
			File file = File.createTempFile("realhowto", ".vbs");
			file.deleteOnExit();
			FileWriter fw = new java.io.FileWriter(file);

			String vbs = "Set objWMIService = GetObject(\"winmgmts:\\\\.\\root\\cimv2\")\n"
					+ "Set colItems = objWMIService.ExecQuery _ \n"
					+ "   (\"Select * from Win32_BaseBoard\") \n"
					+ "For Each objItem in colItems \n"
					+ "    Wscript.Echo objItem.SerialNumber \n"
					+ "    exit for  ' do the first cpu only! \n" + "Next \n";

			fw.write(vbs);
			fw.close();
			Process p = Runtime.getRuntime().exec(
					"cscript //NoLogo " + file.getPath());
			BufferedReader input = new BufferedReader(new InputStreamReader(
					p.getInputStream()));
			String line;
			while ((line = input.readLine()) != null) {
				result += line;
			}
			input.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result.trim();
	}

	
	public static boolean isAllowedAdd(String funcId) {
		
		//ADD USER ROLE AUTENTICATION
		return true;
	}

	public static boolean isAllowedView(String funcId) {
		//ADD USER ROLE AUTENTICATION
		return true;
	}

	public static boolean isAllowedEdit(String funcId) {
		//ADD USER ROLE AUTENTICATION
		return true;
	}

	public static boolean isAllowedDelete(String funcId) {
		//ADD USER ROLE AUTENTICATION
		return true;
	}

	
	public static void main(String[] args) {
		String sn = Util.getSerialNumber("C");
		String snm = Util.getMotherboardSN();
		System.out.println("Serial Motherboard:" + snm);
		System.out.println("Serial Number of C:" + sn);
	}

	public static Date getDateSelection(DateTime dateTimeWidget) {
		Calendar cal = Calendar.getInstance();
		cal.set(Calendar.DAY_OF_MONTH, dateTimeWidget.getDay());
		cal.set(Calendar.MONTH, dateTimeWidget.getMonth());
		cal.set(Calendar.YEAR, dateTimeWidget.getYear());
		cal.set(Calendar.HOUR_OF_DAY, dateTimeWidget.getHours());
		cal.set(Calendar.MINUTE, dateTimeWidget.getMinutes());
		cal.set(Calendar.SECOND, dateTimeWidget.getSeconds());
		return cal.getTime();
	}

	public static void setCmbBasic(TableCombo combo) {
		//combo.getTable().removeAll();
	    combo.defineColumns(new String[] { "kode", "nama" }, new int[] {
	    		SWT.DEFAULT , SWT.DEFAULT });

	    //to hide scroll bar
	    combo.setTableWidthPercentage(92);
		combo.setDisplayColumnIndex(1);
		// turn on the table header.
		combo.setShowTableHeader(true);
		combo.setVisibleItemCount(40);
	}
}
